//
//  EPViewController.m
//  LibraryStorm
//
//  Created by sanghv on 3/29/14.
//  Copyright (c) 2014 tvo. All rights reserved.
//

#import "LSEpubViewController.h"
#import "BookLoader.h"
#import "EPubBookLoader.h"
#import "Chapter.h"
#import "ResourceHelper.h"
#import "FileHelper.h"
#import "SVProgressHUD.h"
#import "HMSegmentedControl.h"
#import "UIColor+HexString.h"
#import "LSArrayDataSource.h"
#import "LSChapterCell.h"

#define Left_Right_Tap_Margin (50.0f + 2*(Left_Padding_Viewer))

static NSString * const ChapterCellIdentifier = @"ChapterCellId";

@interface LSEpubViewController () <UIWebViewDelegate, UIGestureRecognizerDelegate, UITableViewDelegate, ChapterDelegate>
{
    NSString *fontName;
    NSString *backgound;
    NSString *textColor;
}
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@property (weak, nonatomic) IBOutlet UIView *bottomToolbar;
@property (weak, nonatomic) IBOutlet UISlider *pageSlider;
@property (weak, nonatomic) IBOutlet UIView *topToolBar;
@property (weak, nonatomic) IBOutlet HMSegmentedControl *segmentedControl;
@property (weak, nonatomic) IBOutlet UILabel *currentPageDisplayLbl;

@property (weak, nonatomic) IBOutlet UIView *containView;
@property (weak, nonatomic) IBOutlet UITableView *contentsTableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomLayoutToolbar;

@property (nonatomic, retain) BookLoader *bookLoader;
@property (strong, nonatomic) LSArrayDataSource *chaptersArrayDataSource;
@property (strong, nonatomic) NSMutableArray *contentsAndBookmarksList;

@property BOOL epubLoaded;
@property BOOL paginating;
@property BOOL enablePaging;
@property BOOL searching;
@property BOOL nexting;
@property BOOL isClearWebViewContent;
@property int currentSpineIndex;
@property int currentPageInSpineIndex;
@property int pagesInCurrentSpineCount;
@property int currentTextSize;
@property int totalPagesCount;
@property int oldTargetPage;
@property EpubUtilities epubUtilities;
@property PageTurnStyle pageTurnStyle;

@end

@implementation LSEpubViewController
@synthesize bookLoader;
@synthesize webView;
@synthesize pageSlider;
@synthesize segmentedControl;
@synthesize topToolBar;
@synthesize bottomToolbar;
@synthesize currentPageDisplayLbl;
@synthesize containView;
@synthesize contentsTableView;
@synthesize epubLoaded;
@synthesize paginating;
@synthesize enablePaging;
@synthesize searching;
@synthesize nexting;
@synthesize currentSpineIndex;
@synthesize currentPageInSpineIndex;
@synthesize pagesInCurrentSpineCount;
@synthesize currentTextSize;
@synthesize totalPagesCount;
@synthesize isClearWebViewContent;
@synthesize oldTargetPage;
@synthesize epubUtilities;
@synthesize pageTurnStyle;
@synthesize contentsAndBookmarksList;

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    [self setListBarItem:@[@(BarItemButton_Back)/*, @(BarItemButton_Share)*/]];

    // Support iOS 7
    if (SD_IS_IOS7) {
        self.edgesForExtendedLayout = UIRectEdgeAll;
        self.extendedLayoutIncludesOpaqueBars = YES;
        self.automaticallyAdjustsScrollViewInsets = NO;
    }

    self.enablePaging = YES;
    self.isClearWebViewContent = NO;

    webView.scrollView.scrollEnabled = NO;
    webView.scrollView.bounces = NO;
    webView.opaque = NO;

	currentTextSize = IS_DEVICE_IPAD ? [[(kAppDelegate).generalSetting objectForKey:TextSize] intValue] + 6 : [[(kAppDelegate).generalSetting objectForKey:TextSize] intValue];

    UISwipeGestureRecognizer* rightSwipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(gotoNextPage)];
	[rightSwipeRecognizer setDirection:UISwipeGestureRecognizerDirectionLeft];

	UISwipeGestureRecognizer* leftSwipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(gotoPrevPage)];
	[leftSwipeRecognizer setDirection:UISwipeGestureRecognizerDirectionRight];

    UITapGestureRecognizer* tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapHandle:)];
	[tapRecognizer setNumberOfTapsRequired:1];
    [tapRecognizer setNumberOfTouchesRequired:1];
    tapRecognizer.delegate = self;

	[webView addGestureRecognizer:rightSwipeRecognizer];
	[webView addGestureRecognizer:leftSwipeRecognizer];
    [webView addGestureRecognizer:tapRecognizer];

    [pageSlider setMinimumValue:0];
    [pageSlider setMaximumValue:100];
    [pageSlider setMinimumTrackTintColor:[UIColor whiteColor]];
    [pageSlider addTarget:self action:@selector(slidingEnded:) forControlEvents:UIControlEventTouchUpInside];
    [pageSlider addTarget:self action:@selector(slidingEnded:) forControlEvents:UIControlEventTouchUpOutside];
    [pageSlider addTarget:self action:@selector(slidingChanged:) forControlEvents:UIControlEventValueChanged];
    [pageSlider addTarget:self action:@selector(slidingStarted:) forControlEvents:UIControlEventTouchDown];

    // Custom bottom toolbar
    [bottomToolbar setBackgroundColor:Orange_Color_Alpha];

    // Custom top toolbar
    [topToolBar setBackgroundColor:Orange_Color_Alpha];

    // Custom segmented controll
    [segmentedControl setSectionTitles:@[NSLocalizedString(@"NowReading", @"Now Reading"),
                                         NSLocalizedString(@"Contents", @"Contents")
                                         /*NSLocalizedString(@"Bookmarks", @"Bookmarks"),*/
                                         ]];

    segmentedControl.selectionStyle = HMSegmentedControlSelectionStyleTextWidthStripe;
    segmentedControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;
    segmentedControl.scrollEnabled = NO;
    [segmentedControl setSelectionIndicatorColor:[UIColor whiteColor]];
    [segmentedControl setBackgroundColor:[UIColor clearColor]];
    [segmentedControl setFont:Roboto_Bold(IS_DEVICE_IPAD ? 22 : 15.0f)];
    [segmentedControl setSelectedTextColor:[UIColor whiteColor]];
    [segmentedControl setTextColor:[UIColor whiteColor]];
    [segmentedControl addTarget:self action:@selector(segmentedControlChangedValue:) forControlEvents:UIControlEventValueChanged];

    // Custom current page display label
    [currentPageDisplayLbl setFont:Roboto_Regular(IS_DEVICE_IPAD ? 24.0f : 17.0f)];

    contentsAndBookmarksList = [NSMutableArray array];
    [self setupTableView];

    // TODO: Custom webView
    fontName = [kAppDelegate fontFamilyNameWithType:[[(kAppDelegate).generalSetting objectForKey:FontFace] intValue]];
    backgound = @"";
    textColor = @"";
    switch ([[(kAppDelegate).generalSetting objectForKey:Theme] integerValue]) {
        case ThemeStyle_Black:
            backgound = @"000000" ;
            textColor = @"ffffff";

            break;
        case ThemeStyle_White:
            backgound = @"ffffff";
            textColor = @"000000";

            break;
        case ThemeStyle_Sepia:
            backgound = [Color_Sepia_View lowercaseString];
            textColor = @"000000";

            break;
        default:
            break;
    }
    [self.view setBackgroundColor:[UIColor colorWithHexString:backgound]];
    [webView setBackgroundColor:[UIColor colorWithHexString:backgound]];

    [contentsTableView setContentInset:UIEdgeInsetsMake(0, 0, Height_Banner, 0)];

    pageTurnStyle = (PageTurnStyle)[[(kAppDelegate).generalSetting objectForKey:PageTurn] integerValue];
    nexting = YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self loadBook:self.filePath];

    [self showNowReading:YES];
}

- (void)viewDidDisappear:(BOOL)animated {
    [webView loadHTMLString:@"" baseURL:nil];
    [super viewDidDisappear:animated];
}

- (void)dealloc {
    webView = nil;
    _filePath = nil;

    bookLoader = nil;
    _chaptersArrayDataSource = nil;

    [contentsAndBookmarksList removeAllObjects];
    contentsAndBookmarksList = nil;
}

- (void)showNowReading:(BOOL)show {
    [containView setHidden:show];
}

- (void)goBack:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)clickShareButton:(id)sender {

}

- (void)loadChapterWithIndex:(int)index {
    [self loadSpine:index atPageIndex:0];
}

- (void) loadBook:(NSString *)path {
    [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeGradient];

    currentSpineIndex = 0;
    currentPageInSpineIndex = 0;
    pagesInCurrentSpineCount = 0;
    totalPagesCount = 0;
	searching = NO;
    epubLoaded = NO;

    self.isClearWebViewContent = YES;
    [webView loadHTMLString:NSLocalizedString(@"loading data", nil) baseURL:nil];

    [NSThread detachNewThreadSelector:@selector(start:) toTarget:self withObject:path];
}

-(void)start:(NSString *)path {
    self.bookLoader = [[EPubBookLoader alloc] initWithPath:path];

    if(bookLoader.error == 1){
        [webView loadHTMLString:NSLocalizedString(@"parse_error", nil) baseURL:nil];
    }else{
        epubLoaded = YES;

        //record history
        NSMutableArray *items = [FileHelper getDataFromFile:@"history"];
        if(items.count < 100){
            NSArray *array = [path componentsSeparatedByString:@"/"];

            for(NSDictionary *item in items){
                if([[item objectForKey:@"name"] isEqualToString:[array objectAtIndex:(array.count-1)]]){
                    [FileHelper deleteData:item ofFile:@"history"];
                }
            }
            NSMutableDictionary *book = [[NSMutableDictionary alloc] init];
            [book setObject:[array objectAtIndex:(array.count-1)] forKey:@"name"];
            [book setObject:path forKey:@"path"];

            [FileHelper prependData:book toFile:@"history"];
        }

        //set last read page parameters
        [self toLastReadPage];
        if(currentSpineIndex > bookLoader.spineArray.count-1){
            currentSpineIndex = 0;
        }

        [self performSelectorOnMainThread:@selector(updatePagination) withObject:nil waitUntilDone:NO];
    }
}

- (void)reloadDataTableViewWithArray:(NSArray *)newList {
    if ([contentsAndBookmarksList count] > 0) {
        [contentsAndBookmarksList removeAllObjects];
    }
    [contentsAndBookmarksList addObjectsFromArray:newList];

    [contentsTableView reloadData];
}

- (void)setupTableView
{
    TableViewCellConfigureBlock configureCell = ^(LSChapterCell *cell, Chapter *chapter) {
        [cell setDataForCellWithObject:chapter];
    };

    self.chaptersArrayDataSource = [[LSArrayDataSource alloc] initWithItems:contentsAndBookmarksList
                                                          cellIdentifier:ChapterCellIdentifier
                                                      configureCellBlock:configureCell];
    contentsTableView.dataSource = self.chaptersArrayDataSource;
}

#pragma mark - Actions
- (void)segmentedControlChangedValue:(HMSegmentedControl *)sender {
    [self showNowReading:!sender.selectedSegmentIndex];
    epubUtilities = (EpubUtilities)sender.selectedSegmentIndex;
    switch (sender.selectedSegmentIndex) {
        case EpubUtilities_NowReading:
            [self tapHandle:nil];

            break;
        case EpubUtilities_Contents:
            [self reloadDataTableViewWithArray:bookLoader.spineArray];

            break;
        case EpubUtilities_Bookmarks:
            [self reloadDataTableViewWithArray:nil];

            break;
        default:
            break;
    }
}

- (void) slidingStarted:(id)sender{
    int targetPage = 0;
//    NSString *text;

    if(enablePaging){
        targetPage = ((pageSlider.value/(float)100)*(float)totalPagesCount);
        if (targetPage==0) {
            targetPage++;
        }
//        text = [NSString stringWithFormat:@"%d/%d", targetPage, totalPagesCount];

    }else{
        targetPage = ((pageSlider.value/(float)100)*(float)pagesInCurrentSpineCount);
        if (targetPage==0) {
            targetPage++;
        }
//        text = [NSString stringWithFormat:@"%d/%d", targetPage, pagesInCurrentSpineCount];
    }
}

- (void) slidingChanged:(id)sender{
    int targetPage = 0;
	int chapterIndex = 0;
	int pageIndex = 0;
//    NSString *text;

    if(enablePaging){
        targetPage = ((pageSlider.value/(float)100)*(float)totalPagesCount);
        if (targetPage==0) {
            targetPage++;
        }

//        text = [NSString stringWithFormat:@"%d/%d", targetPage, totalPagesCount];
        [currentPageDisplayLbl setText:[NSString stringWithFormat:@"%d / %d", targetPage, totalPagesCount]];

        int pageSum = 0;
        for(chapterIndex=0; chapterIndex<[bookLoader.spineArray count]; chapterIndex++){
            pageSum += ((Chapter *)[bookLoader.spineArray objectAtIndex:chapterIndex]).pageCount;
            if(pageSum>=targetPage){
                pageIndex = ((Chapter *)[bookLoader.spineArray objectAtIndex:chapterIndex]).pageCount - 1 - pageSum + targetPage;
                break;
            }
        }

    }else{
        targetPage = ((pageSlider.value/(float)100)*(float)pagesInCurrentSpineCount);
        if (targetPage==0) {
            targetPage++;
        }
//        text = [NSString stringWithFormat:@"%d/%d", targetPage, pagesInCurrentSpineCount];

        pageIndex = targetPage-1;
    }

    currentPageInSpineIndex = pageIndex;
}

- (void) slidingEnded:(id)sender {
    int targetPage = 0;
	int chapterIndex = 0;
	int pageIndex = 0;
    NSString *text;

    if(enablePaging){
        targetPage = ((pageSlider.value/(float)100)*(float)totalPagesCount);
        if (targetPage==0) {
            targetPage++;
        }

        text = [NSString stringWithFormat:@"%d/%d", targetPage, totalPagesCount];

        int pageSum = 0;
        for(chapterIndex=0; chapterIndex<[bookLoader.spineArray count]; chapterIndex++){
            pageSum += ((Chapter *)[bookLoader.spineArray objectAtIndex:chapterIndex]).pageCount;
            if(pageSum>=targetPage){
                pageIndex = ((Chapter *)[bookLoader.spineArray objectAtIndex:chapterIndex]).pageCount - 1 - pageSum + targetPage;
                break;
            }
        }
    }
    else{
        targetPage = ((pageSlider.value/(float)100)*(float)pagesInCurrentSpineCount);
        if (targetPage==0) {
            targetPage++;
        }
        text = [NSString stringWithFormat:@"%d/%d", targetPage, pagesInCurrentSpineCount];

        pageIndex = targetPage-1;
    }
    NSLog(@"%@", text);

    // TODO: Keep older target page
    nexting = oldTargetPage < targetPage;
    oldTargetPage = targetPage;

    currentPageInSpineIndex = pageIndex;

	[self loadSpine:chapterIndex atPageIndex:currentPageInSpineIndex];
}

#pragma mark - ChapterDelegate
- (void) chapterDidFinishLoad:(Chapter *)chapter{
    totalPagesCount+=chapter.pageCount;

	if(chapter.chapterIndex + 1 < [bookLoader.spineArray count]){
		[[bookLoader.spineArray objectAtIndex:chapter.chapterIndex+1] setDelegate:self];
		[[bookLoader.spineArray objectAtIndex:chapter.chapterIndex+1] loadChapterWithWindowSize:webView.bounds fontPercentSize:currentTextSize];
	} else {
        [pageSlider setValue:(float)100*(float)[self getGlobalPageCount]/(float)totalPagesCount animated:YES];
        [currentPageDisplayLbl setText:[NSString stringWithFormat:@"%d / %d", [self getGlobalPageCount], totalPagesCount]];
		paginating = NO;
        [SVProgressHUD dismiss];
		NSLog(@"Pagination Ended!");
	}
}

- (int) getGlobalPageCount{
	int pageCount = 0;
	for(int i=0; i<currentSpineIndex; i++){
		pageCount += ((Chapter *)[bookLoader.spineArray objectAtIndex:i]).pageCount;
	}
	pageCount+=currentPageInSpineIndex+1;
	return pageCount;
}

- (void) loadSpine:(int)spineIndex atPageIndex:(int)pageIndex {
	NSURL* url = [NSURL fileURLWithPath:[[bookLoader.spineArray objectAtIndex:spineIndex] spinePath]];
	self.isClearWebViewContent = NO;
    
    [webView loadRequest:[NSURLRequest requestWithURL:url]];
	currentPageInSpineIndex = pageIndex;
	currentSpineIndex = spineIndex;
}

- (void) gotoPageInCurrentSpine:(int)pageIndex{
    if(pageIndex == -1){
        pageIndex = pagesInCurrentSpineCount-1;
        currentPageInSpineIndex = pageIndex;
    }

	if(pageIndex>=pagesInCurrentSpineCount){
		pageIndex = pagesInCurrentSpineCount - 1;
		currentPageInSpineIndex = pagesInCurrentSpineCount - 1;
	}

	float pageOffset = pageIndex*webView.bounds.size.width;

    switch (pageTurnStyle) {
        case PageTurnStyle_Slide:
            [self createAnimatedWithType:kCATransitionPush subType:(nexting ? kCATransitionFromRight : kCATransitionFromLeft) duration:0.5f forKey:nil];

            break;
        case PageTurnStyle_Fade:
            [self createAnimatedWithType:kCATransitionFade subType:nil duration:0.5f forKey:nil];

            break;
        case PageTurnStyle_Curl:
            [self createAnimatedWithType:(nexting ? @"pageCurl" : @"pageUnCurl") subType:@"fromRight" duration:1.0f forKey:nil];

            break;
        default:
            break;
    }
    NSString* goToOffsetFunc = [NSString stringWithFormat:@" function pageScroll(xOffset){ window.scroll(xOffset,0); } "];
    NSString* goTo =[NSString stringWithFormat:@"pageScroll(%f)", pageOffset];

    [webView stringByEvaluatingJavaScriptFromString:goToOffsetFunc];
    [webView stringByEvaluatingJavaScriptFromString:goTo];

    if(!enablePaging){
        [pageSlider setValue:(float)100*(float)(currentPageInSpineIndex+1)/(float)pagesInCurrentSpineCount animated:YES];
    }else{
        if(!paginating){
            [pageSlider setValue:(float)100*(float)[self getGlobalPageCount]/(float)totalPagesCount animated:YES];
            [currentPageDisplayLbl setText:[NSString stringWithFormat:@"%d / %d", [self getGlobalPageCount], totalPagesCount]];
        }
    }

    [self recordLastReadPage];
}

#pragma mark - Animated
- (void)createAnimatedWithType:(NSString *)type subType:(NSString*)subtype duration:(CFTimeInterval)duration forKey:(NSString *)key {
    CATransition *animation = [CATransition animation];
    [animation setDuration:duration];

    animation.startProgress = 0;
    animation.endProgress = 1;

    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];

    animation.type = type;
    animation.subtype = subtype;

    [animation setFillMode:@"extended"];

    [webView.layer addAnimation:animation forKey:key];
}

- (void) gotoNextSpine {
	if(!paginating){
		if(currentSpineIndex+1<[bookLoader.spineArray count]){
			[self loadSpine:++currentSpineIndex atPageIndex:0];
		}
	}
}

- (void) gotoPrevSpine {
	if(!paginating){
		if(currentSpineIndex-1>=0){
			[self loadSpine:--currentSpineIndex atPageIndex:0];
		}
	}
}

- (void)gotoNextPage {
    nexting = YES;
    [self tapHandle:nil];
    if(!paginating){
        if(currentPageInSpineIndex+1<pagesInCurrentSpineCount){
            [self gotoPageInCurrentSpine:++currentPageInSpineIndex];
        } else {
            [self gotoNextSpine];
        }
    }
}

- (void)gotoPrevPage {
    nexting = NO;
    [self tapHandle:nil];
	if (!paginating) {
		if(currentPageInSpineIndex-1>=0){
			[self gotoPageInCurrentSpine:--currentPageInSpineIndex];
		} else {
            if(enablePaging){
                if(currentSpineIndex!=0){
                    int targetPage = ((Chapter *)[bookLoader.spineArray objectAtIndex:(currentSpineIndex-1)]).pageCount;
                    [self loadSpine:--currentSpineIndex atPageIndex:targetPage-1];
                }
            }else{
                if(currentSpineIndex-1>=0)
                    [self loadSpine:--currentSpineIndex atPageIndex:-1];
            }
		}
	}
}

- (void)tapHandle:(UIGestureRecognizer *)gesture {
    if (!gesture) {
        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];
        [self.navigationController setNavigationBarHidden:YES animated:YES];
        [UIView animateWithDuration:UINavigationControllerHideShowBarDuration
                         animations:^{
                             _bottomLayoutToolbar.constant = -(bottomToolbar.bounds.size.height);
                         }
                         completion:^(BOOL finished){
                             [self.topToolBar setHidden:YES];
                         }];
    }
    else {
        __block BOOL navigationBarHidden = self.navigationController.navigationBar.hidden;
        [UIView animateWithDuration:UINavigationControllerHideShowBarDuration
                         animations:^{
                             _bottomLayoutToolbar.constant = navigationBarHidden ? 0.0f : -(bottomToolbar.bounds.size.height);
                         }
                         completion:^(BOOL finished){
                             [self.topToolBar setHidden:!navigationBarHidden];
                         }];

        CGPoint touchPoint = [gesture locationInView:webView];
        if (touchPoint.x > webView.bounds.size.width - (Left_Right_Tap_Margin)) {
            [self gotoNextPage];
        }
        else if (touchPoint.x < (Left_Right_Tap_Margin)) {
            [self gotoPrevPage];
        }
        else {
            [[UIApplication sharedApplication] setStatusBarHidden:!self.navigationController.navigationBar.hidden withAnimation:UIStatusBarAnimationFade];
            [self.navigationController setNavigationBarHidden:!self.navigationController.navigationBar.hidden animated:YES];
        }
    }
}

- (void)updatePagination{
	if(epubLoaded){
        if(!paginating){
            NSLog(@"Pagination Started!");

            if(enablePaging){
                if (![SVProgressHUD isVisible]) {
                    [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeGradient];
                }

                totalPagesCount=0;
                paginating = YES;

                [[bookLoader.spineArray objectAtIndex:0] setDelegate:self];
                [[bookLoader.spineArray objectAtIndex:0] loadChapterWithWindowSize:webView.bounds fontPercentSize:currentTextSize];
            }
            [webView loadHTMLString:@"" baseURL:nil];

            [self loadSpine:currentSpineIndex atPageIndex:currentPageInSpineIndex];

            NSLog(@"pages:%d",currentSpineIndex);
        }
	}
}

-(void)toLastReadPage{
    NSMutableDictionary *last = (NSMutableDictionary *)[ResourceHelper getUserDefaults:self.bookLoader.filePath];
    if(last!=nil){
        currentSpineIndex       = [[last objectForKey:@"currentSpineIndex"] intValue];
        currentTextSize         = IS_DEVICE_IPAD ? [[(kAppDelegate).generalSetting objectForKey:TextSize] intValue] + 6 : [[(kAppDelegate).generalSetting objectForKey:TextSize] intValue]/*[[last objectForKey:@"currentTextSize"] intValue]*/;
        currentPageInSpineIndex = [[last objectForKey:@"currentPageInSpineIndex"] intValue];
    }
}

-(void)recordLastReadPage{
    NSMutableDictionary *last = [[NSMutableDictionary alloc] init];
    NSString *rCurrentSpineIndex = [[NSString alloc] initWithFormat:@"%d",currentSpineIndex];
    NSString *rCurrentPageInSpineIndex = [[NSString alloc] initWithFormat:@"%d",currentPageInSpineIndex];
    NSString *rCurrentTextSize = [[NSString alloc] initWithFormat:@"%d",currentTextSize];

    [last setObject:rCurrentSpineIndex forKey:@"currentSpineIndex"];
    [last setObject:rCurrentPageInSpineIndex forKey:@"currentPageInSpineIndex"];
    [last setObject:rCurrentTextSize forKey:@"currentTextSize"];

    [ResourceHelper setUserDefaults:last forKey:self.bookLoader.filePath];
}

- (void)webViewDidFinishLoad:(UIWebView *)theWebView {
    if(self.isClearWebViewContent)
        return;
    
    [webView stringByEvaluatingJavaScriptFromString:[[NSString alloc] initWithContentsOfURL:(kAppDelegate).createCssRule encoding:NSUTF8StringEncoding error:nil]];

	NSString *insertRule1 = [NSString stringWithFormat:@"addCSSRule('html', 'margin: 0px; padding: %fpx %fpx %fpx %fpx; height: %fpx; -webkit-column-gap: %fpx; -webkit-column-width: %fpx;')", Top_Padding_Viewer, Left_Padding_Viewer, 0.0f, Left_Padding_Viewer, webView.frame.size.height - (Top_Padding_Viewer) - (Height_Banner), 2*(Left_Padding_Viewer), webView.frame.size.width];
	NSString *insertRule2 = @"addCSSRule('p', 'text-align: justify;')";
    NSString *insertRule3 = @"addCSSRule('img', 'height: auto; width: auto; max-width: 100%; max-height: 100%; border: none;')";
    NSString *setTextSizeRule = [NSString stringWithFormat:@"addCSSRule('body', 'color: %@; background: #%@; font-weight: normal; font-family: %@; font-size: %dpx;')", textColor, backgound, fontName, currentTextSize];
	NSString *setHighlightColorRule = @"addCSSRule('highlight', 'background-color: yellow;')";

	[webView stringByEvaluatingJavaScriptFromString:insertRule1];
	[webView stringByEvaluatingJavaScriptFromString:insertRule2];
	[webView stringByEvaluatingJavaScriptFromString:insertRule3];
    [webView stringByEvaluatingJavaScriptFromString:setTextSizeRule];
    [webView stringByEvaluatingJavaScriptFromString:setHighlightColorRule];

	int totalWidth = [[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.scrollWidth"] intValue];
	pagesInCurrentSpineCount = (int)((float)totalWidth/webView.bounds.size.width);

    if(currentPageInSpineIndex > pagesInCurrentSpineCount-1)
        currentPageInSpineIndex = pagesInCurrentSpineCount -1;
	[self gotoPageInCurrentSpine:currentPageInSpineIndex];
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (epubUtilities) {
        case EpubUtilities_Contents:
            [self loadChapterWithIndex:(int)[indexPath row]];
            [segmentedControl setSelectedSegmentIndex:0 animated:YES];
            [self segmentedControlChangedValue:segmentedControl];

            break;
        case EpubUtilities_Bookmarks:

            break;

        default:
            break;
    }
}

#pragma mark - Orientation
- (BOOL)shouldAutorotate {
    return YES;
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
    [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
    [self updatePagination];
}

@end
